import glob
import json
import requests
import time
from collections import defaultdict


url = "http://0.0.0.0:8084/infer"


class Timer(object):
    """A simple timer."""
    def __init__(self):
        self.total_time = 0.
        self.calls = 0
        self.start_time = 0.
        self.diff = 0.
        self.average_time = 0.

    def tic(self):
        # using time.time instead of time.clock because time time.clock
        # does not normalize for multithreading
        self.start_time = time.time()

    def toc(self, average=True):
        self.diff = time.time() - self.start_time
        self.total_time += self.diff
        self.calls += 1
        self.average_time = self.total_time / self.calls
        if average:
            return self.average_time
        else:
            return self.diff


def infer(image, question, context=""):

    payload = {'question': question, 'context': context}
    files = [('picture', ('test.jpg', open(image, 'rb'), 'image/jpeg'))]
    headers = {}
    response = requests.request("POST", url, headers=headers, data=payload, files=files, stream=True)

    return response.text


def test():
    image = "./merlion.png"
    questions = ["详细描述图片内容。", "介绍图片"]
    context = ''
    kwargs = {}
    # kwarg = dict(do_sample=True)

    timers = defaultdict(Timer)
    for i in range(10):
        question = questions[i % 2]
        timers['infer_timer'].tic()
        output = infer(image, question, context)
        print(output)
        timers['infer_timer'].toc()
        print(' | {}: {:.3f}s'.format('infer_timer', timers['infer_timer'].average_time))


if __name__ == "__main__":
    test()
